<template>
  <div class="my-applications-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="工作流名称">
            <el-input
              v-model="searchForm.workflowName"
              placeholder="请输入工作流名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="工单状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="运行中" value="running" />
              <el-option label="已暂停" value="pause" />
              <el-option label="待审批" value="approving" />
              <el-option label="已完成" value="complete" />
              <el-option label="已拒绝" value="reject" />
              <el-option label="已取消" value="cancel" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度">
            <el-select
              v-model="searchForm.priority"
              placeholder="请选择紧急程度"
              clearable
              style="width: 120px"
            >
              <el-option label="全部" :value="undefined" />
              <el-option label="紧急" :value="1" />
              <el-option label="普通" :value="0" />
              <el-option label="低" :value="-1" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.createDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="RefreshRight">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 申请列表 -->
    <div class="applications-list-container">
      <el-card>
        <template #header>
          <div class="card-header">
            <span class="card-title">申请列表</span>
            <span class="applications-count">共 {{ total }} 条申请</span>
          </div>
        </template>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 申请表格 -->
        <div v-else-if="applicationsList.length > 0">
          <el-table
            :data="applicationsList"
            stripe
            style="width: 100%"
            @row-click="handleRowClick"
          >
            <el-table-column prop="workflowName" label="工作流名称" min-width="150">
              <template #default="{ row }">
                <div class="workflow-name-cell">
                  <el-icon class="workflow-icon" color="#409eff">
                  </el-icon>
                  <span class="workflow-name">{{ row.workflowName }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag 
                   :type="getStatusType(row.status)" 
                   :class="getStatusClass(row.status)"
                   size="small"
                   class="status-tag"
                 >
                   <div class="status-content">
                     <span class="status-text">{{ getStatusLabel(row.status) }}</span>
                   </div>
                 </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="currentNode" label="当前节点" width="120">
              <template #default="{ row }">
                <span class="current-node">{{ row.currentNodeName || '-' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="priority" label="紧急程度" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityType(row.priority)" size="small">
                  {{ getPriorityLabel(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="createdAt" label="申请时间" width="160">
              <template #default="{ row }">
                <span class="created-time">{{ formatDate(row.createTime) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="updatedAt" label="更新时间" width="160">
              <template #default="{ row }">
                <span class="updated-time">{{ formatDate(row.updateTime) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button
                    size="small"
                    type="primary"
                    text
                    @click.stop="handleViewDetail(row)"
                  >
                    查看详情
                  </el-button>
                  
                  <el-button
                    v-if="row.status === 'running' || row.status === 'approving'"
                    size="small"
                    type="danger"
                    text
                    @click.stop="handleCancel(row)"
                  >
                    取消申请
                  </el-button>
                  
                  <el-button
                    v-if="canResubmit(row)"
                    size="small"
                    type="success"
                    text
                    @click.stop="handleResubmit(row)"
                  >
                    重新申请
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无申请记录">
            <el-button type="primary" @click="$router.push('/workflow/start')">
              去申请
            </el-button>
          </el-empty>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 申请详情弹窗 -->
    <ApplicationDetailDialog
      v-model:visible="detailDialogVisible"
      :application="selectedApplication"
      @refresh="handleRefresh"
      source="myApplications"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  RefreshRight,
  Loading,
  VideoPause,
  Clock,
  CircleCheck,
  CircleClose,
  Close
} from '@element-plus/icons-vue'
import ApplicationDetailDialog from './components/ApplicationDetailDialog.vue'
import { cancelWorkflowInstance, getMyWorkflowInstances } from '/@/api/workflow'
import type { WorkflowInstance } from './types'

// 响应式数据
const loading = ref(false)
const applicationsList = ref<WorkflowInstance[]>([])
const total = ref(0)
const detailDialogVisible = ref(false)
const selectedApplication = ref<WorkflowInstance | null>(null)

// 搜索表单
const searchForm = reactive({
  workflowName: '',
  status: '',
  priority: undefined,
  createDateRange: null as [string, string] | null
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20
})

// 方法
const fetchApplicationsList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      workflowName: searchForm.workflowName,
      status: searchForm.status,
      priority: searchForm.priority,
      createStartDate: searchForm.createDateRange?.[0] || undefined,
      createEndDate: searchForm.createDateRange?.[1] || undefined
    }
    
    const response = await getMyWorkflowInstances(params)
    applicationsList.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('获取申请列表失败')
    console.error('获取申请列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchApplicationsList()
}

const handleRefresh = () => {
  fetchApplicationsList()
}

const handleReset = () => {
  searchForm.workflowName = ''
  searchForm.status = ''
  searchForm.priority = undefined
  searchForm.createDateRange = null
  pagination.page = 1
  fetchApplicationsList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchApplicationsList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchApplicationsList()
}

const handleRowClick = (row: WorkflowInstance) => {
  handleViewDetail(row)
}

const handleViewDetail = (application: WorkflowInstance) => {
  selectedApplication.value = application
  detailDialogVisible.value = true
}

const handleCancel = async (application: WorkflowInstance) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消申请"${application.workflowName}"吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用取消申请的API
    cancelWorkflowInstance({
      id: application.id
    })
    ElMessage.success('申请已取消')
    // 延迟刷新,避免立即刷新后台还没处理完
    setTimeout(() => {
      fetchApplicationsList()
    }, 1000)
  } catch {
    // 用户取消操作
  }
}

const handleResubmit = (application: WorkflowInstance) => {
  // TODO: 实现重新申请逻辑
  ElMessage.info('重新申请功能开发中')
}

const canResubmit = (application: WorkflowInstance) => {
  return application.status === 'reject' || application.status === 'cancel'
}

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    running: 'primary',
    pause: 'warning', 
    approving: 'warning',
    complete: 'success',
    reject: 'danger',
    cancel: 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusClass = (status: string) => {
  return `status-${status}`
}

const getStatusIcon = (status: string) => {
  const iconMap: Record<string, string> = {
    running: 'Loading',
    pause: 'VideoPause',
    approving: 'Clock',
    complete: 'CircleCheck',
    reject: 'CircleClose',
    cancel: 'Close'
  }
  return iconMap[status] || null
}

const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    running: '运行中',
    pause: '已暂停',
    approving: '待审批', 
    complete: '已完成',
    reject: '已拒绝',
    cancel: '已取消'
  }
  return labelMap[status] || status
}

const getPriorityType = (priority: number | string) => {
  const typeMap: Record<number | string, string> = {
    1: 'danger',
    0: '',
    '-1': 'info',
    // 兼容旧的字符串格式
    'urgent': 'danger',
    'normal': '',
    'low': 'info'
  }
  return typeMap[priority] || ''
}

const getPriorityLabel = (priority: number | string) => {
  const labelMap: Record<number | string, string> = {
    1: '紧急',
    0: '普通',
    '-1': '低',
    // 兼容旧的字符串格式
    'urgent': '紧急',
    'normal': '普通',
    'low': '低'
  }
  return labelMap[priority] || '普通'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch {
    return '-'
  }
}

// 生命周期
onMounted(() => {
  fetchApplicationsList()
})
</script>

<style scoped>
.my-applications-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-container {
  margin-bottom: 20px;
}

.applications-list-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.applications-count {
  color: #909399;
  font-size: 14px;
}

.loading-container {
  padding: 20px;
}

.workflow-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workflow-icon {
  flex-shrink: 0;
}

.workflow-name {
  font-weight: 500;
  color: #303133;
}

.current-node {
  color: #606266;
}

.created-time,
.updated-time {
  color: #909399;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.empty-state {
  padding: 40px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 状态样式 */
:deep(.status-tag) {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  min-width: 80px !important;
  padding: 4px 8px !important;
  text-align: center !important;
}

.status-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 100%;
  text-align: center;
}

.status-icon {
  font-size: 12px;
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
}

.status-text {
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  text-align: center;
  line-height: 1;
}

:deep(.status-running) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-color: #409eff;
  color: white;
  animation: pulse 2s infinite;
}

:deep(.status-pause) {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
  border-color: #e6a23c;
  color: white;
}

:deep(.status-approving) {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  border-color: #f56c6c;
  color: white;
  animation: blink 1.5s infinite;
}

:deep(.status-complete) {
  background: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
  border-color: #67c23a;
  color: white;
}

:deep(.status-reject) {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  border-color: #f56c6c;
  color: white;
}

:deep(.status-cancel) {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%);
  border-color: #909399;
  color: white;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.6;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .my-applications-container {
    padding: 12px;
  }

  .search-container :deep(.el-form) {
    flex-direction: column;
  }

  .search-container :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }

  .pagination-container {
    :deep(.el-pagination) {
      justify-content: center;
      flex-wrap: wrap;
    }
  }
}
</style>